package sdk.webview.fmc.com.fmcsdk.check.activity;

import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_NOTIFY_H5_BACK;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.camera.SystemUtils;
import sdk.webview.fmc.com.fmcsdk.check.adapter.DeviceHealthCardAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.TypeSelectAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.ActivityJsonBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.RunListPagerBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.TypeSelectBean;
import sdk.webview.fmc.com.fmcsdk.check.dialog.BottomPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.HealthHistoryView;
import sdk.webview.fmc.com.fmcsdk.check.persenter.HealthHistoryPersenter;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;

public class DeviceHealthCardActivity extends BaseActivity<HealthHistoryView, HealthHistoryPersenter> implements HealthHistoryView, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    private TextView mTvTitle;


    private DeviceHealthCardAdapter workHistoryAdapter;
    private ImageView mIvBack;
    private RecyclerView mRvHistory;
    String assetId;
    private String type = "1,2,3,4,5,6,8,9";
    private String projId;
    private String description;


    private RunListPagerBean workHistoryBean;
    private SwipeRefreshLayout mSelView;
    private EditText mEtSearch;
    private TextView mTvShai;
    private ImageView mIvClear;
    private TextView mTvCancel;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_health_card;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }

        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            Method method = imm.getClass().getMethod("setCustomImeOptions", TextView.class, String.class);
            method.invoke(imm, mEtSearch, "actionSearch;actionLabel=搜索");
        } catch (Exception e) {
            e.printStackTrace();
            // 反射失败处理
        }
        assetId = getIntent().getStringExtra("assetId");
        projId = getIntent().getStringExtra("projId");
        initView();
        initRecycler();
        showLoading();
        initListener();
        requestApi(true);
        ActivityJsonBean bean = new DatabaseManager(context).getUserByName(getClass().getSimpleName());
        if (bean != null) {
            if (!TextUtils.isEmpty(bean.getJson())) {
                workHistoryBean = GsonUtil.GsonToBean(bean.getJson(), RunListPagerBean.class);
                getHistory(workHistoryBean, true);
            }
        }


    }

    private void initRecycler() {
        mRvHistory.setLayoutManager(new LinearLayoutManager(context));
        workHistoryAdapter = new DeviceHealthCardAdapter(null);
        mRvHistory.setAdapter(workHistoryAdapter);
        workHistoryAdapter.setEmptyView(View.inflate(context, R.layout.empty_health, null));
        workHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                RunListPagerBean.RecordsDTO item = workHistoryAdapter.getItem(position);
                if (null != item){
                    if ((item.getOperateType().equals("SUBCHECK") || (item.getOperateType().equals("SUBAPPR")) && !StringUtils.isEmpty(item.getWfEntityId()))){
                        //跳转详情
                        Intent intent = new Intent(context,ApprovalAcceptanceHistoryActivity.class);
                        intent.putExtra("wfEntityId",item.getWfEntityId());
                        intent.putExtra("ownerId",item.getRefId());
                        intent.putExtra("projId",item.getProjId());
                        startActivity(intent);
                    }else {
                        String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                        if (item.getType().equals("8") || item.getType().equals("7") && !StringUtils.isEmpty(item.getRefId())){
                            //跳转巡检详情
                            Intent intent = new Intent(context, CheckDetailsActivity.class);
                            intent.putExtra("id",item.getRefId());
                            intent.putExtra("isFromDeviceHealthCard",true);
                            startActivity(intent);

                        }else if (item.getType().equals("5") && !StringUtils.isEmpty(item.getRefId())){
                            String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken()+"#/reportSrtask/detail/"+item.getRefId()+"?from=app";
                            goH5Activity(h5Url);

                        }else if (item.getType().equals("4") && !StringUtils.isEmpty(item.getRefId())){
                            String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken()+"#/workDetail/"+item.getRefId()+"?from=app";
                            goH5Activity(h5Url);
                        }
                    }
                }

            }
        });
    }

    private void goH5Activity(String url){
        Intent intents = new Intent();
        intents.putExtra(Constant.H5_URL, url);
        intents.setClass(context, H5Activity.class);
        startActivity(intents);
    }
    private void requestApi(boolean isRefresh) {
        presenter.getDetails(isRefresh, assetId, type, projId, description);
    }


    private void initView() {
        mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText(getResources().getString(R.string.Operation_History));
        mIvBack = findViewById(R.id.iv_back);
        mRvHistory = findViewById(R.id.rv_history);



        mSelView = findViewById(R.id.sel_view);
        mEtSearch = findViewById(R.id.et_search);
        mTvShai = findViewById(R.id.tv_shai);
        mIvClear = findViewById(R.id.iv_clear);
        mTvCancel = findViewById(R.id.tv_cancel);
    }

    private void initListener() {
        mTvShai.setOnClickListener(v -> {
            showBottomPopupWindow(v);
        });
        findViewById(R.id.iv_back).setOnClickListener(v -> {
            finish();
            EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_NOTIFY_H5_BACK, ""));
        });
        mSelView.setOnRefreshListener(this);
        workHistoryAdapter.setOnLoadMoreListener(this);
        mTvCancel.setOnClickListener(v -> {
            type = "1,2,3,4,5,6,8,9";
            description = "";
            mEtSearch.setText("");
            mIvClear.setVisibility(View.GONE);
            mTvCancel.setVisibility(View.GONE);
            SystemUtils.hideInputmethod(mEtSearch);
            requestApi(true);
        });

        mIvClear.setOnClickListener(v -> {
            mEtSearch.setText("");
            SystemUtils.hideInputmethod(mEtSearch);
            type = "1,2,3,4,5,6,8,9";
            description = "";
            mEtSearch.setText("");
            mIvClear.setVisibility(View.GONE);
            mTvCancel.setVisibility(View.GONE);
            SystemUtils.hideInputmethod(mEtSearch);
            requestApi(true);

        });
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    description = mEtSearch.getText().toString();
                    requestApi(true);
                    SystemUtils.hideInputmethod(mEtSearch);
                    return true; // 表示已经处理了事件
                }
                return false; // 表示没有处理事件
            }
        });
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                    if (TextUtils.isEmpty(mEtSearch.getText().toString())) {
                        mIvClear.setVisibility(View.GONE);
                        mTvCancel.setVisibility(View.GONE);
                    } else {
                        mIvClear.setVisibility(View.VISIBLE);
                        mTvCancel.setVisibility(View.VISIBLE);
                    }

            }
        });

    }

    public static void startActivity(Context context, String assetId, String projId) {
        Intent intent = new Intent(context, DeviceHealthCardActivity.class);
        intent.putExtra("assetId", assetId);
        intent.putExtra("projId", projId);
        context.startActivity(intent);
    }


    @Override
    protected HealthHistoryPersenter createPresenter() {
        return new HealthHistoryPersenter();
    }

    @Override
    public void getHistory(RunListPagerBean bean, boolean isRefresh) {
        // Collections.reverse(bean.getRecords());
        hideLoading();
        showRefreshView(false);
        if (isRefresh) {
            new DatabaseManager(context).upsertJson(getClass().getSimpleName(), GsonUtil.BeanToJson(bean));
            workHistoryAdapter.setNewData(bean.getRecords());
        } else {
            if (!Utils.isEmpty(bean.getRecords())) {
                workHistoryAdapter.addData(bean.getRecords());
                workHistoryAdapter.loadMoreComplete();
            } else {
                workHistoryAdapter.loadMoreEnd();
            }
        }


    }

    public void showRefreshView(Boolean refresh) {
        if (null == mSelView || null == workHistoryAdapter) return;
        mSelView.post(() -> {
            if (null == mSelView || null == workHistoryAdapter) return;
            mSelView.setRefreshing(refresh);
            workHistoryAdapter.setEnableLoadMore(!refresh);
        });
    }

    @Override
    public void onRefresh() {
        requestApi(true);
    }

    @Override
    public void onLoadMoreRequested() {
        requestApi(false);
    }

    private BottomPopupWindow bottomPopupWindow;
    private boolean isAll;

    private void showBottomPopupWindow(View anchor) {
        if (bottomPopupWindow == null) {
            bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_type_select);
            View view = bottomPopupWindow.getContentView();
            ImageView iv_check_all = view.findViewById(R.id.iv_check_all);
            RecyclerView rv_content = view.findViewById(R.id.rv_content);
            rv_content.setLayoutManager(new LinearLayoutManager(context));
            TypeSelectAdapter adapter = new TypeSelectAdapter(Utils.getTypeList());
            rv_content.setAdapter(adapter);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter ad, View view, int position) {
                    TypeSelectBean bean= adapter.getData().get(position);
                    bean.setSelect(!bean.isSelect());;
                    boolean isNoSelect = adapter.setSelectNo(position);
                    if (!isNoSelect) {
                        iv_check_all.setImageResource(R.mipmap.icon_check_red);
                    } else {
                        iv_check_all.setImageResource(R.mipmap.icon_select_no);
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
                bottomPopupWindow.dismiss();
            });
            view.findViewById(R.id.tv_sure).setOnClickListener(v -> {
                type = adapter.getSelectType();
                bottomPopupWindow.dismiss();
                requestApi(true);

            });
            view.findViewById(R.id.ll_all).setOnClickListener(v -> {
                if(isAll){
                    adapter.setSelectAll(false);
                    isAll=false;
                    iv_check_all.setImageResource(R.mipmap.icon_select_no);
                }else{
                    adapter.setSelectAll(true);
                    isAll=true;
                    iv_check_all.setImageResource(R.mipmap.icon_check_red);
                }

            });

        }
        bottomPopupWindow.show(anchor);
    }
}
